import MSData
import WorkerMSAPI
import WorkerPCNMySQL
import MSLogger
import MSDBTemplates
import MSConfig

import time
import os
import sys
import heartbeating

heartbeat = heartbeating.HeartbeatListener(17202)
heartbeat.start()

MSLogger.logInit('C:\\safe\\ms.cargoreader.log', 2, True)
MSLogger.logInfo('ms driver started')

reader = WorkerMSAPI.Worker()
reader.connect()

objects = MSConfig.readObjectsConfig('etalon_objects.cfg')
writer = WorkerPCNMySQL.Worker('localhost', 'Path to DB', 'user', 'pwd')

for o in objects:
    o.enableOfflineCritical = True

try:
    while True:
        reader.readEventsGPS(objects)
        cursor = writer.connecton.cursor()
        for o in objects:
            for e in o.eventsGPS:
                try:
                    query = "INSERT INTO events (lat,lon,speed) VALUES ('%s','%s','%s')" % (str(e.GPSLatitude), str(e.GPSLongitude), str(e.GPSSpeed))
                    cursor.execute(query)
                except Exception, err:
                    MSLogger.logError('error when parsing obj events: %s', str(err))
                    continue
        writer.connection.commit()
        reader.finalyze(objects)
        time.sleep(15)
except KeyboardInterrupt:
    MSLogger.logError('ms daemon stopped')
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
except Exception, err:
    shr = str(err)[0:100]
    MSLogger.logError('ms driver fatal error: %s' % (str(err)))
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')

